import React, {FC, useEffect, useImperativeHandle, useState} from "react";
import {
    Button,
    Form,
    Input,
    message,
    Modal,
    Radio,
    Select,
    Slider,
    Upload,
    UploadFile,
    UploadProps
} from "antd";
import styles from './index.module.less'
import {workshopElementsInstanceApi} from "../../../../apis/workshop";
import {CloseOutlined, MinusCircleOutlined, PlusOutlined} from "@ant-design/icons";
import {Graph} from "@antv/x6";
import _ from "lodash";
import {RcFile} from "antd/es/upload";
import {uploadFileApi} from "../../../../apis/upload";

interface WorkshopLayoutInfoBasicsProps {
    id?: string
    treeType: string
    visible?: boolean
    onRef?: any
    onChange: (res: Graph.BackgroundManager.Options) => void;
    onSuccess: () => void
}

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = error => reject(error);
    });

export interface Options {
    color: string,
    image: string | undefined,
    opacity: number,
    size: {
        width: number,
        height: number
    },
}

/**
 * 基础信息
 * @param props
 * @constructor
 */
const WorkshopLayoutInfoBasics: FC<WorkshopLayoutInfoBasicsProps> = (props) => {
    const [form] = Form.useForm();
    const {validateFields, resetFields, setFieldsValue} = form;
    const visibleStyle = {display: 'flex', overflow: 'visible', height: '100%', flexDirection: "column", padding: "24px"};
    const unVisibleStyle = {display: 'flex', overflow: 'auto', height: '0px'};
    const [attachment, setAttachment] = useState<UploadFile[]>([]);
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const [backgroundImageUrl, setBackgroundImageUrl] = useState<any>()
    const [backgroundOptions, setBackgroundOptions] = useState<Options>({
        color: '#ffffff',
        image: undefined,
        opacity: 1,
        size: {
            width: 1375,
            height: 775
        },
    })

    const formItemLayout = {
        labelCol: {
            xs: {span: 24},
            sm: {span: 8},
        },
        wrapperCol: {
            xs: {span: 24},
            sm: {span: 16},
        },
    };

    const formItemLayoutForRemark = {
        labelCol: {},
        wrapperCol: {},
    };

    const uploadButtonProps: UploadProps = {
        beforeUpload: async (file: any) => {
            let canUploadFlag = true
            if (canUploadFlag && file.size > 50 * 1024 * 1024) {
                message.error(`上传的文件大小最大50MB`);
                canUploadFlag = false
            }
            return canUploadFlag || Upload.LIST_IGNORE;
        },
        customRequest: (param: { file: string | Blob; }) => {
            const formData = new FormData();
            formData.append("file", param.file);
            uploadFileApi.uploadFile(formData, 0)
                .then((res: any) => {
                    let uploadFile: UploadFile = {
                        uid: res.fileId,
                        name: res.fileName,
                        url: res.url,
                    }
                    setAttachment(_.concat(attachment, uploadFile))
                })
                .catch((ex) => {
                    message.error(ex.message);
                })
        },
        showUploadList: false,
    }

    useEffect(() => {
        if (props.id) {
            handleInit()
        }
    }, [props.id])

    useEffect(() => {
        notifyChange()
    }, [backgroundOptions])

    const handleInit = () => {
        workshopElementsInstanceApi.queryById(props.id).then((res: any) => {
            if (res) {
                setFieldsValue(res)
                if (res.backgroundImageUrl) {
                    setFileList([{
                        uid: '1',
                        name: 'image.png',
                        status: 'done',
                        url: res.backgroundImageUrl,
                    }])
                } else {
                    setFileList([])
                }

                let url = ''
                if (res.backgroundImageUrl) {
                    url = res.backgroundImageUrl.split("/").slice(3).join("/")
                }
                let data = _.cloneDeep(backgroundOptions)
                data.color = res.backgroundColor
                data.opacity = res.opacity
                data.image = url
                setBackgroundOptions(data)

                setAttachment([]);
                if (res.files) {
                    let attachmentArray: UploadFile[] = [];
                    _.forEach(res.files, (vo) => {
                        let uploadFile: UploadFile = {
                            uid: vo.fileId,
                            name: vo.fileName,
                            url: vo.url,
                        }
                        attachmentArray.push(uploadFile);
                    })
                    setAttachment(attachmentArray);
                }
            } else {
                resetFields()
            }
        })
    }

    const handleSubmit = () => {
        validateFields().then((values) => {
            let fileIdList: any[] = [];
            _.forEach(attachment, (file) => {
                fileIdList.push(file.uid);
            });
            let data = {
                ...values,
                id: props.id,
                fileIdList: fileIdList,
                backgroundImageUrl: backgroundImageUrl ? backgroundImageUrl : ""
            }
            workshopElementsInstanceApi.updateById(data).then((res: any) => {
                message.success(`保存成功`)
                props.onSuccess();
            }).catch((ex) => {
                message.error(ex.message);
            });
        })
    }

    const notifyChange = () => {
        props.onChange(backgroundOptions);
    }

    useImperativeHandle(props.onRef, () => {
        return {
            handleSubmit: handleSubmit,
        };
    });

    const handleRemoveFile = (file: any) => {
        const index = attachment!.indexOf(file);
        const newAttachment = attachment!.slice();
        newAttachment.splice(index, 1);
        setAttachment(newAttachment);
    };


    const onColorChanged = (e: any) => {
        let data = _.cloneDeep(backgroundOptions)
        data!.color = e.target.value
        setBackgroundOptions(data)
    };

    const onOpacityChanged = (opacity: number) => {
        let data = _.cloneDeep(backgroundOptions)
        data!.opacity = opacity
        setBackgroundOptions(data)
    };

    const normFile = (e: any) => {
        if (Array.isArray(e)) {
            return e
        }

        return e && e.fileList;
    }
    const handleBeforeUpload = async (file: any) => {
        const imageTypeArr = ['image/png', 'image/jpeg', 'image/jpg']
        let canUploadFlag = true
        if (_.intersection(imageTypeArr, [file.type]).length == 0) {
            message.error(`${file.name} is not png、jpeg、jpg`);
            canUploadFlag = false
        }

        if (canUploadFlag && file.size > 5 * 1024 * 1024) {
            message.error(`上传的文件大小最大5MB`);
            canUploadFlag = false
        }

        return canUploadFlag || Upload.LIST_IGNORE;
    }

    const handleOnPreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewVisible(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };

    const handleCustomRequest = (param: { file: string | Blob; }) => {
        if (!param.file) {
            return;
        }

        let form = new FormData();
        form.append("scene", "deviceScene")
        form.append("file", param.file);
        uploadFileApi.uploadFile(form, 0).then((res?: any) => {
            if (res) {
                setFieldsValue({
                    "imagePath": res.url
                })

                setBackgroundImageUrl(res.url)
                if (res.url) {
                    let data = _.cloneDeep(backgroundOptions)
                    const url = res.url.split("/").slice(3).join("/")
                    data!.image = url
                    setBackgroundOptions(data)
                }
                const tempFileList = _.cloneDeep(fileList)
                tempFileList.forEach(item => {
                    item.status = 'done'
                })
                setFileList(tempFileList)

            }
        }).catch(async (ex) => {
            const tempFileList = _.cloneDeep(fileList)
            tempFileList.forEach(item => {
                item.status = 'error'
            })
            setFileList(tempFileList)

            message.error(ex.message)
        })
    }

    const handleOnRemove = () => {
        setFieldsValue({
            imagePath: null
        })
        let data = _.cloneDeep(backgroundOptions)
        data!.image = undefined
        setBackgroundOptions(data)
        setBackgroundImageUrl(undefined)
        setFileList([])
    }

    const handleOnChange: UploadProps['onChange'] = ({fileList: newFileList}) => {
        setFileList(newFileList);
    }

    const uploadButton = (
        <div>
            <PlusOutlined/>
            <div style={{marginTop: 1}}>Upload</div>
        </div>
    );

    const handleCancel = () => {
        setPreviewVisible(false)
    }
    return (<div style={props.visible ? visibleStyle : unVisibleStyle}>
        <Form
            className={styles.content}
            {...formItemLayout}
            colon={false}
            form={form}
            name="register"
            scrollToFirstError
            labelAlign={"left"}
        >
            <Form.Item label={`名称`} name={`name`} style={{marginBottom: 10}}>
                <Input placeholder="请输入名称"/>
            </Form.Item>
            <Form.Item label={`价格`} name={`price`} style={{marginBottom: 10}}>
                <Input placeholder="请输入价格"/>
            </Form.Item>
            <Form.Item label={`编号`} name={`code`} style={{marginBottom: 10}}>
                <Input placeholder="请输入编号"/>
            </Form.Item>
            <Form.Item label={`状态`} name={`state`} style={{marginBottom: 10}}>
                <Radio.Group buttonStyle="solid">
                    <Radio.Button value="STARTUP">开机</Radio.Button>
                    <Radio.Button value="SHUTDOWN">关机</Radio.Button>
                    <Radio.Button value="MAINTAIN">维护</Radio.Button>
                </Radio.Group>
            </Form.Item>

            <Form.List name={`extend`}>
                {(fields, {add, remove}) => (
                    <>
                        <Form.Item {...formItemLayoutForRemark}>
                            <div style={{
                                display: "flex",
                                flexDirection: "row",
                                alignItems: "center",
                                justifyContent: "space-between"
                            }}>
                                <span style={{fontSize: 14, fontWeight: 550}}>扩展信息</span>
                                <Button style={{width: 80}} onClick={() => add()} icon={<PlusOutlined/>}>
                                    添加
                                </Button>
                            </div>
                        </Form.Item>
                        {fields.map(({key, name, ...restField}) => (
                            <div style={{display: "flex", flexDirection: "row", height: 32, marginBottom: 10}}>
                                <Form.Item {...restField} name={[name, "key"]} style={{flex: '30%'}}>
                                    <Input style={{width: 80}} placeholder="信息1"/>
                                </Form.Item>
                                <Form.Item {...restField} name={[name, "value"]} style={{flex: '60%'}}>
                                    <Input style={{width: 160}} placeholder="信息2"/>
                                </Form.Item>
                                <CloseOutlined style={{height: 32, padding: 10, flex: '10%'}}
                                               onClick={() => remove(name)}/>
                            </div>
                        ))}
                    </>
                )}
            </Form.List>
            <Form.Item name={`remark`}   {...formItemLayoutForRemark}>
                <Input.TextArea placeholder="备注信息" rows={3}/>
            </Form.Item>
            <Form.Item style={{marginBottom: 0}} {...formItemLayoutForRemark}>
                <div style={{
                    display: "flex",
                    flexDirection: "row",
                    alignItems: "center",
                    justifyContent: "space-between"
                }}>
                    <span style={{fontSize: 14}}>要素文件</span>
                    <Upload {...uploadButtonProps}>
                        <Button style={{width: 80}} icon={<PlusOutlined/>}>添加</Button>
                    </Upload>
                </div>
            </Form.Item>
            <Form.Item {...formItemLayoutForRemark}>
                <Upload fileList={attachment} onRemove={handleRemoveFile}>
                </Upload>
            </Form.Item>

            {props.treeType == 'workshop' ?
                <div>
                    <Form.Item label={`背景颜色`} name={`backgroundColor`} initialValue={'#ffffff'}
                               style={{marginBottom: 10}}>
                        <Input
                            type="color"
                            value={backgroundOptions.color}
                            style={{width: "100%"}}
                            onChange={onColorChanged}
                        />
                    </Form.Item>
                    <Form.Item label={'背景图片'} name={'fileList'} valuePropName={"fileList"}
                               getValueFromEvent={normFile}>
                        <Upload
                            name="fileList"
                            listType="picture-card"
                            beforeUpload={handleBeforeUpload}
                            customRequest={handleCustomRequest}
                            onChange={handleOnChange}
                            onPreview={handleOnPreview}
                            onRemove={handleOnRemove}
                            fileList={fileList}
                        >
                            {fileList.length >= 1 ? null : uploadButton}
                        </Upload>
                        <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
                            <img alt="example" style={{width: '100%'}} src={previewImage}/>
                        </Modal>
                    </Form.Item>

                    <Form.Item label={`背景透明度`} name={`opacity`} initialValue={1}
                               style={{marginBottom: 10, width: '95%'}}>
                        <Slider
                            min={0.05}
                            max={1}
                            step={0.05}
                            value={backgroundOptions.opacity}
                            onChange={onOpacityChanged}
                        />
                    </Form.Item>
                </div>
                :
                <div></div>}

        </Form>

        {/*<Settings  onChange={onBackgroundChanged}/>*/}

    </div>)
}
export default WorkshopLayoutInfoBasics
